package com.zlyx.easy.swagger.config;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import com.zlyx.easy.core.list.EasyList;
import com.zlyx.easy.core.list.Lists;
import com.zlyx.easy.core.map.Maps;
import com.zlyx.easy.core.model.ResultModel;
import com.zlyx.easy.swagger.model.ResponseMessage;

import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.service.Parameter;

public class AbstractApiConfiguration implements InitializingBean {

	protected static Map<String, String> tagsNames = Maps.newMap();

	protected static Map<String, ParameterBuilder> parameters = Maps.newMap();

	protected static Map<Integer, ResponseMessage> responseMessages = Maps.newMap();

	protected static EasyList<ResolvedType> models = EasyList.newList();

	protected static ResolvedType defaultResolvedType;

	protected static Class<?> defaultErrorModel = ResultModel.class;

	@Autowired
	protected TypeResolver typeResolver;

	public static ResolvedType getDefaultResolvedType() {
		return defaultResolvedType;
	}

	public static Class<?> getDefaultModel() {
		return defaultErrorModel;
	}

	public static void setDefaultErrorModel(Class<?> defaultErrorModel) {
		AbstractApiConfiguration.defaultErrorModel = defaultErrorModel;
	}

	public static ResolvedType[] getModels() {
		return models.toArray(new ResolvedType[models.size()]);
	}

	public static ResponseMessage getResponseMessage(int code) {
		return responseMessages.get(code);
	}

	public static List<Parameter> getParameters(String[] names) {
		List<Parameter> params = Lists.newList();
		for (String name : names) {
			if (parameters.get(name) != null) {
				params.add(parameters.get(name).name(name).build());
			}
		}
		return params;
	}

	public static String addTagsName(String methodName, String tagsName) {
		return tagsNames.put(methodName, tagsName);
	}

	public static String getTagsName(String methodName) {
		return tagsNames.get(methodName);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		AbstractApiConfiguration.defaultResolvedType = typeResolver.resolve(defaultErrorModel);
	}
}
